﻿using System;
using System.Collections.Generic;
using Codeplus.Library.Models;
using Codeplus.Library.Recaptcha;
using Codeplus.Library.Web;

namespace Codeplus.Library.Controllers
{
    public class Contactus
    {
        public const string PrivateRecaptchaKey = "6Le5zsYSAAAAAKQtXsMkT7VgbSpIxCGYF-pHoQbV";
        public const string RecaptchaPostRequestUrl = "http://www.google.com/recaptcha/api/verify";

        /// <summary>
        /// 
        /// </summary>
        /// <param name="model"></param>
        /// <param name="ipaddress"></param>
        /// <param name="location"></param>
        /// <returns></returns>
        public void CollectContactInfo(ContactUsModel model, string ipaddress, GeolocationModel location)
        {
            if (location != null)
            {
                model.City = location.City;
                model.CountryCode = location.CountryCode;
                model.CountryName = location.CountryName;
                model.Latitude = location.Latitude;
                model.Longitude = location.Longitude;
            }

            try
            {
                model.IPAddress = ipaddress;
                model.NewEnquiry();
            }
            catch (Exception ex)
            {
                //log
                throw new ApplicationException("Failed to save a new enquiry", ex);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="ipaddress"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool IsCaptchaSuccessful(string ipaddress, ContactUsModel model)
        {
            var recaptchPostData = new Dictionary<string, string>();
            recaptchPostData.Add("privatekey", PrivateRecaptchaKey);
            recaptchPostData.Add("remoteip", ipaddress);
            recaptchPostData.Add("challenge", model.Recaptcha.ChallengeField);
            recaptchPostData.Add("response", model.Recaptcha.ResponseField);
            var webRequest = new CustomRequest();
            var response = webRequest.MakeWebRequest(RecaptchaPostRequestUrl,
                                                     CustomRequest.GetPostData(recaptchPostData));
            bool isCaptchaSuccessful = RecaptchaStatusCode.IsSuccessful(response);
            return isCaptchaSuccessful;
        }
    }
}
